package org.example.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author zhengdp
 * @Description 获取Unsafe对象
 * @Date 2022/11/27 20:12
 * @Created by zhengdp
 */
public class UnsafeAccessor {

    static Unsafe unsafe;

    static {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            // 静态成员变量不需要传递对象
            unsafe = (Unsafe) theUnsafe.get(null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    static Unsafe getUnsafe() {
        return unsafe;
    }

}
